package spms.front.config;


import ch.qos.logback.core.ConsoleAppender;
import com.alibaba.fastjson.JSONObject;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

@Component
public class LogConfig extends ConsoleAppender {

	private KafkaTemplate kafkaTemplate;
	public static String port;
	public static String appName;

	@Override
	public void append(Object eventObject) {
		super.append(eventObject);
		/*if(getKafkaTemplate() != null){
			if(eventObject instanceof ch.qos.logback.classic.spi.LoggingEvent){
				ch.qos.logback.classic.spi.LoggingEvent le = (ch.qos.logback.classic.spi.LoggingEvent) eventObject;
				JSONObject job = new JSONObject();
				parseLogbackMsg(le,job);
				kafkaTemplate.sendDefault(job.toJSONString());
			}else if(eventObject instanceof org.slf4j.event.LoggingEvent) {
				org.slf4j.event.LoggingEvent le = (org.slf4j.event.LoggingEvent) eventObject;
				JSONObject job = new JSONObject();
				parseLogMsg(le,job);
				kafkaTemplate.sendDefault(job.toJSONString());
			}
		}*/
	}
	private void parseLogbackMsg(ch.qos.logback.classic.spi.LoggingEvent le,JSONObject job){
		job.put("app",appName);
		job.put("port",port);
		job.put("time",le.getTimeStamp());
		job.put("logger",le.getLoggerName());
		job.put("msg",le.getFormattedMessage());
	}

	private void parseLogMsg(org.slf4j.event.LoggingEvent le, JSONObject job) {
		job.put("app",appName);
		job.put("port",port);
		job.put("time",le.getTimeStamp());
		job.put("logger",le.getLoggerName());
		job.put("msg",le.getMessage());
	}

	public KafkaTemplate getKafkaTemplate() {
		if(kafkaTemplate == null && ContextConfig.applicationContext != null){
			kafkaTemplate = (KafkaTemplate) ContextConfig.applicationContext.getBean("kafkaTemplate");
		}
		return kafkaTemplate;
	}

}
